<template>
  <div>
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :disabled="finished" finished-text="没有更多了">
      <!-- 上拉加载 -->
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" class="box-width">
        <!-- 图片信息组件 -->
        <PictureInfo
        v-for="item in pictureInfo"
            :key="item.id"
            :title="item.name"
            :author="item.author"
            :picture="item.picture"
            :id="item.id"
            :view="item.view"
        ></PictureInfo>
      </van-list>
  </van-pull-refresh>
  </div>
</template>

<script>
import _ from 'lodash'
import PictureInfo from '@/components/PictureInfo/PictureInfo.vue'
let fn = null

export default {
  name: 'Home',
  components: {
    PictureInfo
  },
  data () {
    return {
      // 存储图片信息
      pictureInfo: [],
      // 页码
      page: 1,
      // 每页多少数据
      limit: 4,
      // 是否正在加载下一页数据，如果loading为true，不会反复触发load事件
      // 下一页数据请求回来，要把loading改为false
      loading: true,
      // 所有数据是否加载完了，没有数据把finished改为true
      finished: false,
      // 是否正在下拉刷新
      isLoading: false
    }
  },
  methods: {
    // 获取图片信息
    async getPictureInfo (isRefresh) {
      const page = this.page
      const limit = this.limit
      const { data: res } = await this.$http({
        url: '/picture/pictureInfo',
        method: 'GET',
        params: {
          page,
          limit
        }
      })
      // console.log(res)
      // this.pictureInfo = res.data
      // console.log(this.pictureInfo[0])
      if (isRefresh) {
        // 下拉刷新
        // 新数据在前旧数据在后
        this.pictureInfo = [...res.data, ...this.pictureInfo]
        this.loading = false
        this.isLoading = false
      } else {
        // 上拉加载
        // 旧数据在前新数据在后
        this.pictureInfo = [...this.pictureInfo, ...res.data]
        this.loading = false
      }
      // 没有数据不能加载更多
      if (res.data.length === 0) {
        this.finished = true
      }
    },
    // 上拉加载
    onLoad () {
      // console.log('a')
      this.page++
      this.getPictureInfo()
    },
    // 下拉刷新
    onRefresh () {
      // console.log('a')
      this.page++
      this.getPictureInfo(true)
    },
    // 判断滑轮距离顶端距离
    recordTopHandler () {
      return _.debounce(
        () => {
          // console.log(this.$route.meta.top)
          this.$route.meta.top = window.scrollY
        },
        50,
        { trailing: true }
      )
    }
  },
  created () {
    this.getPictureInfo()
  },
  // 激活时判断距离
  activated () {
    fn = this.recordTopHandler()
    window.addEventListener('scroll', fn)
  },
  // 到别的页面终止执行
  deactivated () {
    window.removeEventListener('scroll', fn)
  }
}
</script>

<style lang="less" scoped>

@media screen and (min-width: 1280px) {
  .box-width{
    margin-left: 10%;
    padding: 20px;
  }
  }
</style>
